package com.example.demo.zaqizabatest;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.math.BigDecimal;
import java.sql.*;
import java.util.Arrays;
import java.util.List;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname DorisJdbcTest
 * @description
 * @date 2024/03/04 15:00
 * <p>
 * ******************************************************
 */
public class DorisJdbcTest {

    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        System.out.println(testJdbcByUnknowColumns("test", "SELECT * FROM test.t8 WHERE r_regionkey > ?", new String[]{"3"}));

    }

    public static String testJdbcByUnknowColumns(String databaseName, String sql, String[] args) throws SQLException, ClassNotFoundException {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection connection = DriverManager.getConnection("jdbc:mysql://10.1.206.133:9030/" + databaseName + "?useServerPrepStmts=true", "root", "");
            PreparedStatement prepareStatement = connection.prepareStatement(sql);
            if (args != null) {
                for (int i = 1; i <= args.length; i++) {
                    prepareStatement.setString(i, args[i-1]);
                }
            }
            ResultSet resultSet = prepareStatement.executeQuery();
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            String[] columnNames = new String[columnCount];
            for (int i = 1; i <= columnCount; i++) {
                String columnName = metaData.getColumnName(i);
                columnNames[i - 1] = columnName;
            }

            StringBuilder res = new StringBuilder();
            while (resultSet.next()) {
                for (String columnName : columnNames) {
                    String value = resultSet.getString(columnName);
                    res.append(columnName).append(" = ").append(value).append(", ");
                }
                res.append("\n");
            }
            return res.toString();
        } catch (Exception e) {
            ByteArrayOutputStream errInfo = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(errInfo));
            return errInfo.toString();
        }
    }
}
